package com.fengye.algorithms.leecode;

import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;

/**
 * @Author fengye
 * @Date 2023/4/10 9:30
 **/
public class FindReplaceString833 {
    public String findReplaceString(String s, int[] indices, String[] sources, String[] targets) {
        Map<Integer,String> map = new TreeMap<>(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1.compareTo(o2);
            }
        });

        for(int i=0;i<indices.length;i++) {
            map.put(indices[i], sources[i] + "_" + targets[i]);
        }

        StringBuilder sb = new StringBuilder(s);
        int startIndex = 0;
        for(Integer key : map.keySet()) {
            int a = key + startIndex;
            String op = map.get(key);
            String[] ops = op.split("_");
            String sub = ops[0];
            String t = ops[1];
            String ss = s.substring(a, a + sub.length());
            if (ss.equals(sub)) {
                sb.replace(a, a + sub.length(), t);
                startIndex += sb.length() - s.length();
                s = sb.toString();
            }
        }

        return sb.toString();
    }
}
